package com.evamay.kotlindemo.service

import android.content.Context
import android.graphics.Bitmap
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.Target
import com.evamay.kotlindemo.utils.FileUtils
import java.io.File
import java.io.FileOutputStream
import java.util.*

class ImagesDownLoadService(private var url: String?, private var context: Context?, private var callBack: DownLoadCallBack?) :Runnable {

    override fun run() {
        var file:File?=null
        var bitmap:Bitmap?=null
        try {
            bitmap=Glide.with(context!!).asBitmap().load(url).into(Target.SIZE_ORIGINAL,Target.SIZE_ORIGINAL).get()
            if (bitmap!=null) {
                saveImageToGallery(context!!,bitmap,url)
                callBack!!.onDownLoadSuccess(bitmap)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            callBack!!.onDownLoadFailed(e.message.toString())
        }

    }

    private fun saveImageToGallery(context: Context, bitmap: Bitmap, url: String?) {
        var fileDir=File(FileUtils.baseFilePath+"images")
        if (fileDir.exists().not()) {
            fileDir.mkdirs()
        }
        var fileType=url!!.substring(url!!.lastIndexOf("."))
        var fileName=System.currentTimeMillis().toString()+".jpg"

        var imageFile=File(FileUtils.baseFilePath+"images/",fileName)
        if (!imageFile.exists()) {
            imageFile.createNewFile()
        }
        var fos=FileOutputStream(imageFile)
        try {

            bitmap.compress(Bitmap.CompressFormat.JPEG,100,fos)
            fos.flush()
            fos.close()

        } catch (e: Exception) {
            e.printStackTrace()
            callBack!!.onDownLoadFailed(e.message.toString())
        }finally {
            fos.flush()
            fos.close()
        }

    }


}